﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Threading;
using System.Text;
using System.Data;
using System.Collections;
namespace Golf.WebUI
{
    public partial class Golfshow : System.Web.UI.Page
    {
        /// <summary>
        /// 页码数
        /// </summary>
        public int Pager
        {
            get
            {
                return int.Parse(ViewState["page"].ToString());
            }
            set
            {
                ViewState["page"] = value;
            }
        }
        /// <summary>
        /// 分页 数字编号
        /// </summary>
        public string _UrlPage = "";
        /// <summary>
        /// 商品ids
        /// </summary>
        public string _Pro_strids;
        /// <summary>
        /// 筛选的产品属性ids
        /// </summary>
        public string _attr_ids = "";
        /// <summary>
        /// 商品类型编号
        /// </summary>
        public int typeid = 0;

        /// <summary>
        /// 当前的商品类型名称
        /// </summary>
        public string _TypeName = "";
        /// <summary>
        /// 更加商品获得的商品属性id
        /// </summary>
        public string[] _pro_attrid = { };
        /// <summary>
        ///   价格查询  促销价一
        /// </summary>
        public decimal _Pro_PromotionPrice_1;
        /// <summary>
        ///    价格查询  促销价二 
        /// </summary>
        public decimal _Pro_PromotionPrice_2;
        private Golf.BLL.Golf_Product bll = new Golf.BLL.Golf_Product();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (_Typeid.Value != "")
            {
                typeid = int.Parse(_Typeid.Value);//将隐藏域中的id给typeid 防止局部刷新之后类型id没有值
                _Pro_strids = Pro_strids();
            }
            if (!Page.IsPostBack)
            {
                if (Request.Params["typeid"] != null && Request.Params["typeid"].Trim() != "")
                {
                    try
                    {
                        typeid = (Convert.ToInt32(Request.Params["typeid"]));
                        if (typeid == 9)
                        {
                            Response.Redirect("Left-Hand.aspx");
                        }
                        _Typeid.Value = typeid.ToString();//将类型id存入隐藏域
                        _Pro_strids = Pro_strids();
                    }
                    catch (Exception)
                    {
                    }
                    Bind_Detail();
                    Bind_allType();
                    //默认页码数为0
                    Pager = 0;
                    //URL分页
                    BindToRepeater();
                    Bind_Customer_Rated_Pro();
                    Bind_Top_Selling();
                }
            }

        }
        #region  页面右边的  卖得最好的 和 客户评价最好的
        /// <summary>
        ///当前类型的商品 卖的最好
        /// </summary>
        public void Bind_Top_Selling()
        {
            DataSet ds = Maticsoft.DBUtility.DbHelperSQL.Query("select b.ProductId,COUNT(*) aa from dbo.Golf_OrderProduct b where b.ProductId in(select id From Golf_Product where Pro_TypeId=" + typeid + ") group by b.ProductId order by aa desc");
            DataTable dt = ds.Tables[0];
            StringBuilder sb = new StringBuilder();
            int rowsCount = dt.Rows.Count;
            if (rowsCount > 0)
            {
                for (int n = 0; n < rowsCount; n++)
                {
                    if (dt.Rows[n]["ProductId"] != null && dt.Rows[n]["ProductId"].ToString() != "")
                    {
                        sb.Append(dt.Rows[n]["ProductId"].ToString() + ",");
                    }
                }
            }
            string sb1 = "";
            if (sb.Length != 0)
            {
                sb1 = sb.ToString().Substring(0, sb.Length - 1);
            }
            else return;
            List<Golf.Model.Golf_Product> list = bll.DataTableToList(bll.GetList(5, " id in(" + sb1 + ")", "Pro_Star desc").Tables[0]);
            foreach (var item in list)
            {
                string[] temp = item.Pro_Picture.Split(',');
                item.Pro_Picture = temp[0];
                //处理 节省值
                item.Pro_Save = Golf.GetSave._GetSave(item.Pro_MarketPrice, (decimal)item.Pro_PromotionPrice);
            }
            Repeater1.DataSource = list;
            Repeater1.DataBind();
        }

        /// <summary>
        /// 客户评论最好的
        /// </summary>
        public void Bind_Customer_Rated_Pro()
        {
            if (IsType())
            {
                Golf.BLL.Golf_Product bll = new Golf.BLL.Golf_Product();
                // 
                List<Golf.Model.Golf_Product> list = bll.DataTableToList(bll.GetList(5, " Pro_TypeId=" + typeid, "  Pro_Star desc").Tables[0]);
                foreach (var item in list)
                {
                    string[] temp = item.Pro_Picture.Split(',');
                    item.Pro_Picture = temp[0];
                    //处理 节省值
                    item.Pro_Save = Golf.GetSave._GetSave(item.Pro_MarketPrice, (decimal)item.Pro_PromotionPrice);
                }
                rep_Cus_best.DataSource = list;
                rep_Cus_best.DataBind();
            }
        }
        #endregion
        #region  页面顶上左边 和页面右边顶上 绑定的类型
        /// <summary>
        /// 绑定类型
        /// </summary>
        public void Bind_allType()
        {
            if (IsType())
            {
                Golf.BLL.Golf_ProductType bll_type = new Golf.BLL.Golf_ProductType();
                DataSet ds = bll_type.GetList(" isshow=1 and IsParent=0"); DataTable dt = ds.Tables[0];

                int rowsCount = dt.Rows.Count;
                if (rowsCount > 0)
                {
                    for (int n = 0; n < rowsCount; n++)
                    {
                        if (typeid.ToString() == dt.Rows[n]["Id"].ToString())
                        {
                            _TypeName = dt.Rows[n]["TypeName"].ToString();
                        }
                    }
                }
                Repeater2.DataSource = ds;
                Repeater2.DataBind();
                rep_alltype.DataSource = ds;
                rep_alltype.DataBind();
            }
        }
        #endregion
        #region  查询商品
        /// <summary>
        /// 商品id
        /// </summary>
        public string attr_for_proid = "";
        /// <summary>
        /// URL分页
        /// </summary>
        public void BindToRepeater()
        {
            List<Golf.Model.Golf_Product> _list = new List<Golf.Model.Golf_Product>();
            Golf.BLL.Golf_Product bll = new Golf.BLL.Golf_Product();

            //每页显示像素
            int myPageSize = this.DevNetPager1.PageSize;
            //当前显示页的索引
            int myPageIndex = this.DevNetPager1.PageIndex;
            string url = HttpContext.Current.Request.Url.AbsolutePath + "?typeid=" + typeid + "&page={0}";
            DevNetPager1.DevWebUrl = url.Substring(1, url.Length - 1);
            DevNetPager2.DevWebUrl = url.Substring(1, url.Length - 1);
            DataSet ds;

            //属性筛选
            if (_attr_ids != "")
            {
                attr_for_proid = Pro_strids_for_attr();
                if (_Pro_PromotionPrice_1 == 0 && _Pro_PromotionPrice_2 == 0)
                    ds = bll.GetList(myPageSize, myPageIndex, "  id in(" + attr_for_proid + ") and Pro_TypeId=" + typeid);
                else
                    ds = bll.GetList(myPageSize, myPageIndex, "  id in(" + attr_for_proid + ") and Pro_TypeId=" + typeid + "and Pro_PromotionPrice>" + _Pro_PromotionPrice_1 + " and Pro_PromotionPrice<" + _Pro_PromotionPrice_2 + "");
                List<Golf.Model.Golf_Product> _attrlist = bll.DataTableToList(ds.Tables[0]);
                //得到改属性下的所有的产品  判断该商品的类型是否为当前的商品类型 如果是 就添加到 数据集中去
                foreach (var item in _attrlist)
                {
                    //if (typeid == item.Pro_TypeId)
                    //{
                    //}
                    string[] temp = item.Pro_Picture.Split(',');
                    item.Pro_Picture = temp[0];

                    //处理 节省值
                    item.Pro_Save = Golf.GetSave._GetSave(item.Pro_MarketPrice, (decimal)item.Pro_PromotionPrice);
                    _list.Add(item);
                }
            }
            else//商品的类型筛选
            {
                if (_Pro_strids == "") return;
                if (_Pro_PromotionPrice_1 == 0 && _Pro_PromotionPrice_2 == 0)
                    ds = bll.GetList(myPageSize, myPageIndex, "  Pro_TypeId=" + typeid);
                else
                    ds = bll.GetList(myPageSize, myPageIndex, "   Pro_TypeId=" + typeid + "and Pro_PromotionPrice>" + _Pro_PromotionPrice_1 + " and Pro_PromotionPrice<" + _Pro_PromotionPrice_2 + "");
                List<Golf.Model.Golf_Product> list = bll.DataTableToList(ds.Tables[0]);
                foreach (var item in list)
                {
                    string[] temp = item.Pro_Picture.Split(',');
                    item.Pro_Picture = temp[0];
                    //处理 节省值
                    item.Pro_Save = Golf.GetSave._GetSave(item.Pro_MarketPrice, (decimal)item.Pro_PromotionPrice);
                }
                _list = list;
            }
            int rowCount = (int)ds.Tables[2].Rows[0][0];//获取第二章表的集合数据
            _pro_attrid = Pro_attrid(_list);
            DevNetPager1.RecordCount = rowCount;//
            DevNetPager2.RecordCount = rowCount;//
            this.rep_proPage.DataSource = _list;
            this.rep_proPage.DataBind();
            Script_Write(_list);
        }
        #endregion
        #region
        /// <summary>
        /// 更加商品获取所有的商品属性  以判断是否启用按钮
        /// </summary>
        /// <returns></returns>
        public string[] Pro_attrid(List<Golf.Model.Golf_Product> list)
        {
            Golf.BLL.Golf_ProAttrDetail bll__ = new Golf.BLL.Golf_ProAttrDetail();
            StringBuilder sb = new StringBuilder();
            foreach (var item in list)
            {
                List<Golf.Model.Golf_ProAttrDetail> attr = bll__.DataTableToList(bll__.GetList("ProId=" + item.Id).Tables[0]);
                foreach (var item_ in attr)
                {
                    sb.Append(item_.DetaileId + ",");
                }
            }
            string[] str__01 = { };
            if (sb.Length != 0)
            {
                str__01 = sb.ToString().Substring(0, sb.Length).Split(',');
            }
            List<string> arrylist = new List<string>();
            for (int i = 0; i < str__01.Length; i++)//去掉重复的 
            {
                if (!arrylist.Contains(str__01[i]))
                    arrylist.Add(str__01[i]);
            }
            string sss = string.Join(",", arrylist.ToArray());//将数组拆分
            return arrylist.ToArray();
        }
        #endregion
        #region  页面注册 js 脚本代码
        /// <summary>
        /// 生成页面脚本    鼠标移动到上面的
        /// </summary>
        public void Script_Write(List<Golf.Model.Golf_Product> list)
        {
            StringBuilder sbScript = new StringBuilder();
            sbScript.Append(" <script language=\"JavaScript\">  \n");
            foreach (var item in list)
            {
                //ID，名称，名优产品，HREF，图片，CommercialMsg，价格，规格，保存，评价，视频，缺货，折扣
                //ID, Name, BrandName, Href, Image, CommercialMsg, Price, RRP, Save, Rating, Video, OOS, Discount
                sbScript.Append("MAD.products.addProduct(new MAD.entities.product(\"" + item.Id + "\", \" " + item.Pro_Name + "\", \"" + new Index().GetBrandName((int)item.Pro_BrandTypeId) + "\", \"ProductDetail.aspx?id=" + item.Id + "\", \"ImageProducts/" + item.Pro_PicBig.Split(',')[0] + "\", \"" + item.Pro_Name + "\", \"" + item.Pro_PromotionPrice + "\", \"" + item.Pro_MarketPrice + "\", \"" + item.Pro_Save + "\", \"" + item.Pro_Star + "\", \"1\")); \n");
            }
            sbScript.Append(" </script> \n");
            script_pro.InnerHtml += sbScript.ToString();
        }
        #endregion

        #region 根据传入页面的商品类型  查询下面商品的属性以及子类属性    方法1：先查询到商品id 在到商品属性中间表中查询父类属性id  取出来 去掉重复的 或者不去掉
        /// <summary>
        /// 根据类型查询 商品id 字符串
        /// </summary>
        /// <returns></returns>
        public string Pro_strids()
        {
            if (IsType())
            {
                Golf.BLL.Golf_Product bll = new Golf.BLL.Golf_Product();
                List<Golf.Model.Golf_Product> list = bll.GetModelList(" Pro_TypeId=" + typeid);
                StringBuilder sb = new StringBuilder();
                foreach (var item in list)
                {
                    sb.Append(item.Id + ",");
                }
                if (sb.Length > 0)
                {
                    return sb.ToString().Substring(0, sb.Length - 1);
                }
                else
                {
                    return sb.ToString();
                }
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 根据  商品属性 返回商品id
        /// </summary>
        /// <returns></returns>
        public string Pro_strids_for_attr()
        {
            StringBuilder sqlwhere = new StringBuilder();
            if (_attr_ids != "")
            {
                string[] attr_s = _attr_ids.Split(',');
                foreach (var item in attr_s)
                {
                    sqlwhere.Append("DetaileId like '%" + item + "%' or ");
                }
                Golf.BLL.Golf_ProAttrDetail proDetail = new Golf.BLL.Golf_ProAttrDetail();
                List<Golf.Model.Golf_ProAttrDetail> list = proDetail.GetModelList(sqlwhere.ToString().Substring(0, sqlwhere.ToString().Length - 3));
                StringBuilder sb = new StringBuilder();
                foreach (var item in list)
                {
                    sb.Append(item.ProId + ",");
                }
                if (sb.Length > 0)
                {
                    return sb.ToString().Substring(0, sb.Length - 1);
                }
                return sb.ToString();
            }
            else
            {
                return "";
            }
        }

        #endregion

        #region  属 性 绑 定
        /// <summary>
        /// 绑定  属性 
        /// </summary>
        public void Bind_Detail()
        {
            Golf.BLL.Golf_Attribute attr_bll = new Golf.BLL.Golf_Attribute();
            DataSet ds;
            /*
            ds = attr_bll.GetList("AttrParent is not null and AttrChild is null");
            rep_attr.DataSource = ds.Tables[0];
            rep_attr.DataBind();
            return;//后面的代码 先不要  但是不要删除了  这个改类型产品的属性
            */

            //产品属性中间表  根据商品id来查询父类属性
            Golf.BLL.Golf_ProAttrDetail proDetail = new Golf.BLL.Golf_ProAttrDetail();
            if (_Pro_strids == "") return;
            List<Golf.Model.Golf_ProAttrDetail> list = proDetail.GetModelList("proid in(" + _Pro_strids + ")");
            StringBuilder sb = new StringBuilder();
            foreach (var item in list)
            {
                sb.Append(item.AttrId + ",");
            }
            if (sb.Length > 0)
            {
                ds = attr_bll.GetList("ID in(" + sb.ToString().Substring(0, sb.Length - 1) + ")");
                rep_attr.DataSource = ds.Tables[0];
                rep_attr.DataBind();
            }
            else if (sb.ToString() != "")
            {
                ds = attr_bll.GetList("ID in(" + sb.ToString() + ")");
                rep_attr.DataSource = ds.Tables[0];
                rep_attr.DataBind();
            }
        }
        /// <summary>
        /// 子类属性名称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rep_attr_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Golf.BLL.Golf_Attribute attr_bll = new Golf.BLL.Golf_Attribute();
            //判断里层repeater处于外层repeater的哪个位置（ AlternatingItemTemplate，FooterTemplate，

            //HeaderTemplate，，ItemTemplate，SeparatorTemplate）
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {

                Repeater rep = e.Item.FindControl("rep_attr_detail") as Repeater;//找到里层的repeater对象
                DataRowView rowv = (DataRowView)e.Item.DataItem;//找到分类Repeater关联的数据项 
                int id = Convert.ToInt32(rowv["ID"]); //获取填充子类的id 
                List<Golf.Model.Golf_Attribute> list = attr_bll.GetModelList("parentid=" + id + " and AttrChild is not null and AttrParent is null");
                rep.DataSource = list;
                rep.DataBind();
            }
        }

        /// <summary>
        ///   属性是否启用代码     没有实现呀 我艹Ta仙人
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rep_attr_detailItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Golf.BLL.Golf_Attribute attr_bll = new Golf.BLL.Golf_Attribute();
            //判断里层repeater处于外层repeater的哪个位置（ AlternatingItemTemplate，FooterTemplate， 
            //HeaderTemplate，，ItemTemplate，SeparatorTemplate）
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                LinkButton linkbtn = e.Item.FindControl("link_attr") as LinkButton;//找到里层的LinkButton对象
                Golf.Model.Golf_Attribute attr_model = (Golf.Model.Golf_Attribute)e.Item.DataItem;
                int id = attr_model.ID;
                foreach (var item in _pro_attrid)
                {
                    if (id != int.Parse(item))
                    {
                        linkbtn.CssClass = "disabled";
                        linkbtn.Enabled = false;
                    }
                }
            }
        }
        #endregion

        #region 判断是否有类型
        /// <summary>
        /// 判断是否有类型
        /// </summary>
        /// <returns></returns>
        public bool IsType()
        {
            Golf.BLL.Golf_ProductType bll = new Golf.BLL.Golf_ProductType();
            Golf.Model.Golf_ProductType model = bll.GetModel(typeid);
            if (model != null && model.Id != 0)
                return true;
            else
                return false;
        }
        #endregion
        /// <summary>
        /// 属性改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void attr_Click(object sender, EventArgs e)
        {
            LinkButton link = (LinkButton)sender;
            if (link.CssClass == "selected")
                link.CssClass = "";
            else
                link.CssClass = "selected";
            _attr_ids = hid_attr.Value;
            BindToRepeater();

            //后台注册脚本块执行。
            //ScriptManager.RegisterStartupScript(this, this.GetType(), "SetTipScript", "zhix()", true);
            udpProducts.Update();
        }

        protected void txtLowerPriceBound_TextChanged(object sender, EventArgs e)
        {
            _Pro_PromotionPrice_1 = decimal.Parse(txtLowerPriceBound.Text);
            _Pro_PromotionPrice_2 = decimal.Parse(txtUpperPriceBound.Text);
            BindToRepeater();
            udpProducts.Update();
        }
    }
}
